package cool.taomu.toolkit.utils

import java.net.Inet4Address
import java.net.Inet6Address
import java.net.NetworkInterface
import java.net.SocketException
import java.util.ArrayList
import org.eclipse.xtend.lib.annotations.Accessors
import org.eclipse.xtend.lib.annotations.ToString
import org.slf4j.LoggerFactory
import org.apache.commons.lang3.exception.ExceptionUtils

class NetworkInterfacesUtils {
    val static LOG = LoggerFactory.getLogger(NetworkInterfacesUtils);

    @Accessors
    @ToString
    static class LocalHost {
        String name;
        String ipv4;
        String ipv6;
        String mac;
    }

    def static getNetworkInterfacesInfo() {
        try {
            var networkInterfaces = NetworkInterface.getNetworkInterfaces();
            var result = new ArrayList<LocalHost>()
            while (networkInterfaces.hasMoreElements()) {
                var networkInterface = networkInterfaces.nextElement();
                var name = networkInterface.getName();
                result.add(getNetworkInterfacesInfoByName(name));
            }
            return result
        } catch (SocketException e) {
            LOG.error(ExceptionUtils.getStackTrace(e))
        }
    }

    def static getNetworkInterfacesInfoByName(String name) {
        var localHost = new LocalHost();
        try {
            localHost.name = name;
            var networkInterface = NetworkInterface.getByName(name); // 替换为实际接口名称
            if (networkInterface !== null) {
                var mac = networkInterface.getHardwareAddress();
                if (mac !== null) {
                    var StringBuilder sb = new StringBuilder();
                    for (var int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac.get(i), (i < mac.length - 1) ? ":" : ""));
                    }
                    localHost.mac = sb.toString();
                }
                var inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    var inetAddress = inetAddresses.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        localHost.ipv4 = inetAddress.getHostAddress();
                    } else if (inetAddress instanceof Inet6Address) {
                        localHost.ipv6 = inetAddress.getHostAddress();
                    }
                }
            } else {
                LOG.info("未找到指定的网络接口");
            }
        } catch (SocketException e) {
            LOG.error(ExceptionUtils.getStackTrace(e))
        }
        LOG.info("网络接口信息:{}", localHost);
        return localHost;
    }

}
